<template>
  <div class="app-container">
    <el-card v-loading="loading">
      <el-input v-model="filterText" placeholder="搜索" />
      <el-tree-v2
        ref="treeRef"
        :height="550"
        :data="dataSource"
        node-key="id"
        accordion
        :default-expanded-keys="[1]"
        class="tree"
        :filter-method="filterNode"
      >
        <template #default="{ data }">
          <div class="custom-tree-node">
            <span>{{ data.name }}</span>
            <div>
              <el-dropdown>
                <el-button style="margin-top: 2.3px" type="primary" link>新增</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="append(data, true)">新增同级节点</el-dropdown-item>
                    <el-dropdown-item @click="append(data, false)">新增子节点</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-button type="primary" link @click.stop="handlerOnEdit(data)">编辑</el-button>
              <el-button type="danger" link @click.stop="remove(data)">删除</el-button>
            </div>
          </div>
        </template>
      </el-tree-v2>
    </el-card>
    <el-dialog v-model="dialogData.visabled" :title="dialogData.title" @close="dialogOnClose">
      <el-form ref="form" :rules="formRules" :model="formData">
        <el-form-item label="地区名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入地区名称" />
        </el-form-item>
        <el-form-item label="地区编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入地区编码" />
        </el-form-item>
        <el-form-item v-if="levelOptions.length" label="上级地区" prop="parentId">
          <el-select v-model="formData.parentId" placeholder="请选择上级地区">
            <el-option
              v-for="item in levelOptions"
              :key="item?.id"
              :label="item?.name"
              :value="item?.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogOnClose">取消</el-button>
          <el-button type="primary" @click="dialogOnConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { ElButton, FormInstance, FormRules } from "element-plus";
import type { RegionType } from "@/api/region/type";
import { deleteRegionById, getRegionById, getRegionList, saveAndUpdateRegion } from "@/api/region";
import { DialogDataType } from "./type";
const loading = ref<boolean>(false);
const dataSource = ref<RegionType[]>([]);
const getData = async () => {
  loading.value = true;
  const data = await getRegionList();
  dataSource.value = data;
  loading.value = false;
};
const form = ref<FormInstance>();

getData();
const formRules = reactive<FormRules<Omit<RegionType, "children">>>({
  name: [
    { required: true, message: "请输入地区名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  code: [{ required: true, message: "请输入地区编码", trigger: "blur" }],
});
const levelOptions = ref<RegionType[]>([]);
const formData = ref<Partial<RegionType>>({});
const dialogData = reactive<DialogDataType>({ visabled: false, title: "新增同级节点" });
const append = async (data: RegionType, isEqualLevel: boolean) => {
  dialogData.visabled = true;
  dialogData.title = isEqualLevel ? "新增同级节点" : "新增子节点";
  if (isEqualLevel) {
    const res = await getRegionById(data.parentId || "-1");
    formData.value = {
      parentId: res?.id ?? 0,
      level: res?.level ?? 1,
    };
    if (res) {
      levelOptions.value = [res];
      formRules.parentId = [{ required: true, message: "请输入地区名称", trigger: "blur" }];
    }
  } else {
    levelOptions.value = [data];
    formData.value = {
      parentId: data.id,
      level: data.level + 1,
    };
  }
};

const handlerOnEdit = async (data: RegionType) => {
  dialogData.visabled = true;
  formData.value = JSON.parse(JSON.stringify(data));
  const res = await getRegionById(data.parentId || "-1");
  if (res) {
    levelOptions.value = [res];
  }
};

const dialogOnClose = () => {
  dialogData.visabled = false;
  formData.value = {};
  levelOptions.value = [];
  form.value?.resetFields();
  form.value?.clearValidate();
  delete formRules.parentId;
};
const dialogOnConfirm = () => {
  form.value?.validate(async (valid) => {
    if (valid) {
      delete formData.value.children;
      const res = await saveAndUpdateRegion(formData.value);
      if (res) {
        dialogOnClose();
        getData();
        ElMessage.success("操作成功");
      }
    }
  });
};
const remove = (data: RegionType) => {
  let message = "确认删除此区域？";
  if (data?.children?.length) {
    message = "该地区下存在子级地区，确认删除此区域？删除后子区域也会被删除！";
  }
  ElMessageBox.confirm(message, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteRegionById(data.id);
      if (res) {
        ElMessage.success("删除成功");
        getData();
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const filterText = ref<string>("");
const treeRef = ref<InstanceType<typeof ElTree>>();
watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
interface Tree {
  [key: string]: any;
}
const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.name?.includes(value);
};
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.tree {
  margin-top: 20px;
  height: 100%;
}
</style>
